package de.steric.battlemon;

import java.text.ParseException;
import java.util.ArrayList;

import org.lwjgl.LWJGLException;

import de.steric.battlemon.rendering.Graphics;
import de.steric.battlemon.rendering.Mesh;

public class Battlemon {

	// einstellungen
	public static final int width = 800, height = 600;
	public static final long fixedTime = 100;// alle 10tel sekunde
	public static final int fps = 60;

	// _____________________________________________________
	public static Battlemon battlemon;

	private Graphics graphics;
	private GameObject szene;

	public GameObject getSzene() {
		return szene;
	}

	public boolean isCloseRequested;

	public Battlemon() {
		battlemon = this;
	}

	public void start() {
		try {
			init();
		} catch (LWJGLException e) {
			System.err.println("Error initializig LWJGL:");
			e.printStackTrace();
			System.exit(1);
		} catch (ParseException e) {
			e.printStackTrace();
			System.exit(1);
		}
		loop();
	}

	private void init() throws LWJGLException, ParseException {
		System.out.println("Initializing Battlemon");
		isCloseRequested = false;
		graphics = new Graphics(this, width, height);
		graphics.start();// startet Graphics Thread
		System.out.println("Waiting for Graphics to Initialize");
		synchronized (battlemon) {
			try {

				wait();// wait for graphics to initialize

			} catch (InterruptedException e1) {
				e1.printStackTrace();
				System.exit(1);
			}
			try {
				setUpSzene();
			} catch (Exception e) {
				System.err.println(e.getMessage());
				e.printStackTrace();
				System.exit(1);
			}
			System.out.println("Waking up Graphics");
			battlemon.notify();
		}
	}

	private void setUpSzene() throws Exception {
		System.out.println("Setting up Szene");
		szene = new OriginGameObject();
		/*StaticObject simon = new StaticObject("Simonsky.obj");

		szene.addChild(simon);*/
	}

	private void loop() {
		System.out.println("Starting Battlemon Loop");
		long lastTime = System.currentTimeMillis(), delta = 0;
		while (!isCloseRequested) {
			update(delta / 1000d);
			delta = System.currentTimeMillis() - lastTime;
			lastTime = System.currentTimeMillis();
			try {
				if (delta < fixedTime)
					Thread.sleep(fixedTime - delta);
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.exit(1);
			}
		}

	}

	public void requestClose() {
		isCloseRequested = true;
	}

	// @param delta time in sec
	private void update(double delta) {
		System.out.println("Update " + delta);
	}
}
